<?php

class AdminController extends BaseController {
        
    public function indexAction($request) {    	
		$this->data['events'] = p1_event::getAll();
				
		if(!p1_admin::isLoggedIn()) {
			BaseController::forward("Admin", "login");
			AdminController::loginAction($request);
			return;
		}
    }
    
    public function loginAction($request) {
    	if(isset($request['username'])) {
    		$user = $request['username'];
    		$pass = isset($request['password']) ? $request['password'] : "";
    		$password = crypt($pass, $user);
    		$admin = p1_admin::get($user, "username");
    		if($admin->exists()) {
    			if($admin->password == $password) {
    				$_SESSION['p1_admin'] = $admin->id;
    				BaseController::redirect("../ranking/");
    			}
    		}
    	}
    }
    
    public function calculateAction($request) { 	
		$this->data['events'] = p1_event::getAll();
				
		if(!p1_admin::isLoggedIn()) {
			BaseController::forward("Admin", "login");
			AdminController::loginAction($request);
			return;
		}
		
		$votes = p1_vote::getAll(array("calculated"=>0));
		if(empty($votes)) {
			BaseController::forward("Admin", "no_votes");
			AdminController::no_votesAction($request);
			return;
		}
		
		$eventsRaw = p1_event::getAll(array(), array(), 150);
		$events = array();
		foreach($eventsRaw as $e) {
			$events[$e->id] = $e;
		}
		
		// set calculation date
		$calc = new p1_calculation(array());
		$calc->save();
		
		// calculate score & vote
		$count = 0;
		foreach($votes as $v) {			
			$events[$v->event]->votes++;
			$events[$v->event]->score += ($v->distance + $v->time_to_complete + $v->terrain + $v->climate + $v->factor + $v->support);
			
			// toogle vote
			$votes[$count]->calculated = $calc->id;
			$votes[$count]->update();
			$count++;
		}
		
		// save scores
		foreach($events as $e) {
			$score = new p1_score(array("calculated"=>$calc->id, "event"=>$e->id, "previous_rank"=>$e->rank));
			$score->score = isset($e->votes) ? ($e->score/$e->votes) : '0.00';
			$score->votes = isset($e->votes) ? $e->votes : '0';
			$score->save();
		}
		
		// update ranks
		$scores = p1_score::getAll(array("calculated"=>$calc->id), array("score", "DESC"));
		$count = 0;
		foreach($scores as $s) {
			$count++;
			$events[$s->event]->rank = $count;
			
			$events[$s->event]->name = addslashes($events[$s->event]->name);
			$events[$s->event]->description = addslashes($events[$s->event]->description);
			$events[$s->event]->update();
		}
		
		BaseController::redirect("../ranking/result/");
    }
    
    public function no_votesAction($request) {     	
    }

}

?>